/**
 *
 */
package org.t2.game.server.module.mail.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.gaming.prefab.mail.MailArgs;
import org.gaming.prefab.mail.MailBelong;
import org.gaming.service.asserts.Asserts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.game.server.foundation.starting.ApplicationSettings;
import org.t2.game.server.module.mail.constant.MailTemplate;
import org.t2.game.server.module.mail.model.Mail;
import org.t2.game.server.module.mail.model.MailSystem;
import org.t2.game.server.module.mail.model.MailSystemResult;
import org.t2.game.server.module.mail.service.MailService;
import org.t2.game.server.module.mail.service.MailSystemResultService;
import org.t2.game.server.module.mail.service.MailSystemService;
import org.t2.game.server.module.player.model.Player;
import org.t2.game.server.module.player.service.PlayerService;
import org.t2.game.server.module.tips.GameCause;
import org.t2.game.server.module.tips.TipsCode;

import sh.t2.share.apiutil.GameApi;
import sh.t2.share.module.mail.MailApiProtocol.MailDeletePlayerRequest;
import sh.t2.share.module.mail.MailApiProtocol.MailDeletePlayerResponse;
import sh.t2.share.module.mail.MailApiProtocol.MailQueryPlayerRequest;
import sh.t2.share.module.mail.MailApiProtocol.MailQueryPlayerResponse;
import sh.t2.share.module.mail.MailApiProtocol.MailSysDeleteRequest;
import sh.t2.share.module.mail.MailApiProtocol.MailSysDeleteResponse;
import sh.t2.share.module.mail.MailApiProtocol.MailToGameRequest;
import sh.t2.share.module.mail.MailApiProtocol.MailToGameResponse;
import sh.t2.share.module.mail.MailAttachment;
import sh.t2.share.module.mail.MailData;

/**
 * @author YY
 *
 */
@Controller
public class MailApi {

	private static Logger logger = LoggerFactory.getLogger(MailApi.class);
	
	@Autowired
	private MailSystemService mailSystemService;
	@Autowired
	private MailSystemResultService mailSystemResultService;
	@Autowired
	private MailService mailService;
	@Autowired
	private ApplicationSettings applicationSettings;
	@Autowired
	private PlayerService playerService;

	/**
	 * 发送系统邮件
	 * @param mailToGameServer
	 * @return
	 */
	@RequestMapping(value = GameApi.sendMailSystem)
	@ResponseBody
	public MailToGameResponse sendMailSystem(@RequestBody MailToGameRequest request) {
		logger.info("收到系统邮件添加请求，后台邮件ID{}", request.id);
		
		MailSystemResult mailSystemResult = mailSystemResultService.getEntity(request.id);
		Asserts.isTrue(mailSystemResult == null, TipsCode.MAIL_SYS_REPEATED);
		
		MailBelong mailBelong = null;
		if (request.type == 1) {
			mailBelong = MailBelong.EVERYONE;
		} else {
			mailBelong = MailBelong.SOMEONE;
		}
		List<RewardThing> rewards = new ArrayList<>();
		if (request.rewards != null) {
			for (MailAttachment attachment : request.rewards) {
				rewards.add(RewardThing.of(attachment.getItem(), attachment.getNum()));
			}
		}
		try {
			Set<Long> pids = new HashSet<>();
			if(request.playerIds != null && !"".equals(request.playerIds)) {
				String[] parts = request.playerIds.split(";");
				for(String part : parts) {
					pids.add(Long.parseLong(part));
				}
			}
			
			mailSystemResult = new MailSystemResult();
			mailSystemResult.setId(request.id);
			mailSystemResultService.insert(mailSystemResult);

			MailSystem mailSystem = mailSystemService.createMail(MailTemplate.SYS, MailArgs.build(request.title),
					MailArgs.build(request.content), mailBelong, pids, rewards, GameCause.MAIL_SYS,
					applicationSettings.getGameServerIds(), request.id);
			mailSystem.setLevel(0);
			mailSystemService.saveMail(mailSystem);
			
			logger.info("系统邮件{}添加成功", request.id);
		} catch (Exception e) {
			Asserts.isTrue(false, TipsCode.MAIL_SYS_EXCEPTION, e.getMessage());
		}
		return new MailToGameResponse();
	}

	/**
	 * 删除系统邮件
	 * @param mailSystemId
	 * @return
	 */
	@RequestMapping(value = GameApi.deleteMailSystem)
	@ResponseBody
	public MailSysDeleteResponse deleteMailSystem(@RequestBody MailSysDeleteRequest request) {
		MailSystem mailSystem = mailSystemService.getMailSystem(request.mailSystemId);
		if (mailSystem != null) {
			mailSystemService.delete(mailSystem);
		}
		return new MailSysDeleteResponse();
	}


	/**
	 * 查询玩家邮件
	 * @param playerId
	 * @return
	 */
	@RequestMapping(value = GameApi.queryPlayerMails)
	@ResponseBody
	public MailQueryPlayerResponse queryPlayerMails(@RequestBody MailQueryPlayerRequest request) {
		Player player = playerService.getEntity(request.playerId);
		List<Mail> mails = mailService.mails(player.getId());
		
		MailQueryPlayerResponse response = new MailQueryPlayerResponse();
		
		for (Mail mail : mails) {
			MailData mailData = new MailData();
			mailData.setId(mail.getId());
			mailData.setReceiver(mail.getReceiver());
			mailData.setTemplate(mail.getTemplate());
			mailData.setTitleArgs(mail.getTitleArgs());
			mailData.setContentArgs(mail.getContentArgs());
			mailData.setAttachment(mail.getAttachment());
			mailData.setRead(mail.isRead() + "");
			mailData.setReceive(mail.isReceive() + "");
			mailData.setExpireTime(mail.getExpireTime());
			mailData.setGameCause(mail.getGameCause());
			mailData.setGameCauseText(mail.getGameCauseText());
			mailData.setFromPoolId(mail.getFromPoolId());
			response.datas.add(mailData);
		}
		return response;
	}

	/**
	 * 删除玩家个人邮件
	 * @param playerId
	 * @param mailId
	 * @return
	 */
	@RequestMapping(value = GameApi.deletePlayerMail)
	@ResponseBody
	public MailDeletePlayerResponse deletePlayerMail(@RequestBody MailDeletePlayerRequest request) {
		Mail mail = mailService.getMail(request.playerId, request.mailId);
		if (mail != null) {
			mailService.delete(Collections.singletonList(mail));
		}
		return new MailDeletePlayerResponse();
	}
}
